package com.easonji.admin.service.impl;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import com.easonji.admin.manager.UserManager;
import com.easonji.admin.model.RolePermission;
import com.easonji.admin.service.RoleService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.easonji.admin.dao.RoleDAO;
import com.easonji.admin.form.RoleForm;
import com.easonji.admin.manager.AppManager;
import com.easonji.admin.mapper.RoleMapper;
import com.easonji.admin.mapper.RolePermissionMapper;
import com.easonji.admin.mapper.UserRoleMapper;
import com.easonji.admin.model.Role;
import com.easonji.admin.model.UserRole;
import com.easonji.admin.query.RoleQuery;
import com.easonji.common.base.service.AbstractBaseService;
import com.easonji.common.constant.Consts;
import com.easonji.common.constant.cache.CacheConsts;
import com.easonji.common.constant.cache.CacheKeyConsts;
import com.easonji.common.node.TreeNode;
import com.easonji.common.util.ConvertUtils;
import com.easonji.common.util.JsonUtils;
import com.easonji.common.util.StringUtils;
import com.easonji.core.annotion.CacheRemove;
import com.easonji.core.exception.BizException;

/**
 * @ClassName: RoleService
 * @Description: 角色服务实现类
 * @Author: LiuJun
 * @date: 2018/07/30 14:06:36
 * @Version: 1.0
 * @Copyright: Copyright (c) 2018 - 2019
 */
@Service
public class RoleServiceImpl extends AbstractBaseService<Role> implements RoleService {

    @Resource
    private RoleMapper roleMapper;

    @Resource
    private RolePermissionMapper rolePermissionMapper;

    @Resource
    private UserRoleMapper userRoleMapper;

    @Resource
    private RoleDAO roleDAO;

    @Resource
    private AppManager appManager;

    @Resource
    private UserManager userManager;

    @Override
    public Object queryRoleList(RoleQuery roleQuery) {
        // 查询条件
        Wrapper<Role> wrapper = new EntityWrapper<>();
        Integer appId = roleQuery.getAppId();
        if (StringUtils.isNotEmpty(appId)) {
            wrapper.eq("app_id", appId);
        }
        String condition = roleQuery.getCondition();
        if (StringUtils.isNotEmpty(condition)) {
            wrapper.like("name", condition);
        }
        // 排序
        List<String> columns = new ArrayList<>();
        columns.add("app_id");
        columns.add("num");
        wrapper.orderAsc(columns);
        List<Role> roles = roleMapper.selectList(wrapper);
        return warp(roles);
    }

    @Override
    public Object queryRole(Integer roleId) {
        Role role = roleMapper.selectById(roleId);
        return warp(role);
    }

    @Override
    @CacheRemove(value = CacheConsts.CONSTS, key = { CacheKeyConsts.ROLE })
    public Integer saveRole(RoleForm roleForm) {
        Role role = new Role();
        BeanUtils.copyProperties(roleForm, role);
        return roleMapper.insert(role);
    }

    @Override
    @CacheRemove(value = CacheConsts.CONSTS, key = { CacheKeyConsts.ROLE })
    public Integer updateRole(RoleForm roleForm) {
        Role role = new Role();
        BeanUtils.copyProperties(roleForm, role);
        return roleMapper.updateById(role);
    }

    @Override
    @Transactional(readOnly = false, rollbackFor = BizException.class)
    @CacheRemove(value = CacheConsts.CONSTS, key = { CacheKeyConsts.ROLE })
    public void removeRole(Integer roleId) {
        // 删除该角色所有的权限
        Wrapper<RolePermission> wrapper = new EntityWrapper<>();
        wrapper.eq("role_id", roleId);
        rolePermissionMapper.delete(wrapper);
        // 删除该角色所有用户
        Wrapper<UserRole> userRoleWrapper = new EntityWrapper<>();
        userRoleWrapper.eq("role_id", roleId);
        userRoleMapper.delete(userRoleWrapper);
        // 删除角色
        roleMapper.deleteById(roleId);
    }

    @Override
    @Transactional(readOnly = false, rollbackFor = BizException.class)
    public void setAuthority(Integer roleId, String permissionIds) {
        // 删除该角色所有的权限
        Wrapper<RolePermission> wrapper = new EntityWrapper<>();
        wrapper.eq("role_id", roleId);
        rolePermissionMapper.delete(wrapper);
        // 添加新的权限
        String[] ids = StringUtils.split(permissionIds, Consts.COMMA);
        for (String id : ids) {
            RolePermission rolePermission = new RolePermission();
            rolePermission.setRoleId(roleId);
            rolePermission.setPermissionId(ConvertUtils.toInt(id));
            rolePermissionMapper.insert(rolePermission);
        }
    }

    @Override
    public List<TreeNode> queryRoleTreeNode(Integer userId) {
        return roleDAO.selectRoleTreeNodesByUserId(userId);
    }

    @Override
    protected JSONObject warp2Json(Role role) {
        JSONObject result = JsonUtils.parseObject(role);
        result.put("appName", appManager.getAppNameById(role.getAppId()));
        return result;
    }
}
